package biz

import (
	"beetle/internal/pkg/tool"
	"encoding/json"
	"fmt"
)

// handleMap 处理map模式的数据
func handleMap(redisKey string, data string) map[string]string {

	list, err := unmarshalSlice(data)
	if err != nil {
		// TODO 记录日志
		return nil
	}

	if !tool.IsValid(redisKey) {
		// TODO 记录日志
		return nil
	}
	result := make(map[string]string)
	var placeholder = tool.Between(redisKey)
	for _, mp := range list {
		for key, val := range mp {
			if key == placeholder {
				// 替换占位符
				cacheKey := tool.Replace(redisKey, placeholder, fmt.Sprint(val))
				result[cacheKey] = marshalMap(mp)
			}
		}
	}
	return result
}

// 处理分组
func handleGroup(redisKey string, data string) map[string]string {
	list, err := unmarshalSlice(data)
	if err != nil {
		// TODO 记录日志
		return nil
	}

	if !tool.IsValid(redisKey) {
		// TODO 记录日志
		return nil
	}

	var placeholder = tool.Between(redisKey)
	var group = make(map[string][]map[string]interface{})
	for _, mp := range list {
		for key, val := range mp {
			if key == placeholder {
				// 替换占位符
				cacheKey := tool.Replace(redisKey, placeholder, fmt.Sprintf("%s:%s", placeholder, val))
				ss := group[cacheKey]
				ss = append(ss, mp)
				group[cacheKey] = ss
			}
		}
	}
	result := make(map[string]string)
	for key, val := range group {
		result[key] = marshalSlice(val)
	}
	return result
}

// MarshalMap 序列化Map
func marshalMap(mp map[string]interface{}) string {
	bytes, err := json.MarshalIndent(mp, "", " ")
	if err != nil {
		// TODO 记录日志
		return ""
	}
	return string(bytes)
}

// marshalSlice 序列化Slice
func marshalSlice(list []map[string]interface{}) string {
	bytes, err := json.MarshalIndent(list, "", " ")
	if err != nil {
		// TODO 记录日志
		return ""
	}
	return string(bytes)
}

// unmarshalSlice 反序列化到Slice
func unmarshalSlice(data string) ([]map[string]interface{}, error) {
	var list []map[string]interface{}
	err := json.Unmarshal([]byte(data), &list)
	return list, err
}
